import os
import json
from typing import Dict, Any
from pathlib import Path

class ConfigManager:
    """配置管理器，读取config.properties文件"""
    
    def __init__(self, config_path: str = "config.properties"):
        self.config_path = Path(config_path)
        self.config = {}
        self.load_config()
        
    def load_config(self):
        """加载配置文件"""
        if not self.config_path.exists():
            raise FileNotFoundError(f"配置文件不存在: {self.config_path}")
            
        with open(self.config_path, 'r', encoding='utf-8') as f:
            for line in f:
                line = line.strip()
                if line and not line.startswith('#') and '=' in line:
                    key, value = line.split('=', 1)
                    key = key.strip()
                    value = value.strip()
                    
                    # 处理环境变量替换
                    if value.startswith('${') and value.endswith('}'):
                        env_var = value[2:-1]
                        value = os.getenv(env_var, value)
                    
                    self.config[key] = value
        
        # 创建必要的目录
        self._create_directories()
    
    def _create_directories(self):
        """创建必要的目录结构"""
        dirs_to_create = [
            'logs',
            'data',
            'data/training_data',
            self.get('DATA_EXPORT_PATH', './data/training_data')
        ]
        
        for dir_path in dirs_to_create:
            Path(dir_path).mkdir(parents=True, exist_ok=True)
    
    def get(self, key: str, default: Any = None) -> Any:
        """获取配置值"""
        return self.config.get(key, default)
    
    def get_int(self, key: str, default: int = 0) -> int:
        """获取整数配置值"""
        try:
            return int(self.get(key, default))
        except (ValueError, TypeError):
            return default
    
    def get_float(self, key: str, default: float = 0.0) -> float:
        """获取浮点数配置值"""
        try:
            return float(self.get(key, default))
        except (ValueError, TypeError):
            return default
    
    def get_bool(self, key: str, default: bool = False) -> bool:
        """获取布尔配置值"""
        value = self.get(key, default)
        if isinstance(value, bool):
            return value
        return str(value).lower() in ('true', '1', 'yes', 'on')
    
    def get_model_paths(self) -> Dict[str, str]:
        """获取所有模型路径"""
        return {
            'qwen_omni': self.get('MODEL_QWEN_OMNI_PATH'),
            'deepseek_r1': self.get('MODEL_DEEPSEEK_R1_PATH'),
            'llama_long': self.get('MODEL_LLAMA_LONG_PATH'),
            'deepseek_coder': self.get('MODEL_DEEPSEEK_CODER_PATH')
        }

# 全局配置实例
config = ConfigManager()